package cn.liufuwen.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;

import cn.liufuwen.domain.Goods;
import cn.liufuwen.domain.Orders;
import cn.liufuwen.domain.OrdersDetail;
import cn.liufuwen.entity.OrdersDTO;
import cn.liufuwen.mapper.GoodsMapper;
import cn.liufuwen.mapper.OrdersDetailMapper;
import cn.liufuwen.mapper.OrdersMapper;
import cn.liufuwen.service.OrdersService;
import lombok.extern.java.Log;
@Log
//注册为 Dubbo 服务
@Service(version = "${demo.service.version}")  
public class OrdersServiceImpl implements OrdersService {
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private OrdersDetailMapper ordersDetailMapper;
	@Autowired
    private GoodsMapper goodsMapper;
	@Override
	public List<OrdersDTO> listOrders(int userId) {
		List<Orders> listOrders = ordersMapper.selectListOrdersByUserID(userId);
		List<OrdersDTO> listOrdersDTO =  new ArrayList<OrdersDTO>();
		for(Orders o:listOrders){
			log.info(o.toString());
			OrdersDTO ot = new OrdersDTO();
			ot.setId(o.getId());
			ot.setOrderAmount(o.getOrderAmount().toString());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date dt = new Date();
			if(o.getCreateTime()!=null){
				dt = o.getCreateTime();
				ot.setCreateTime(sdf.format(dt));
			}else{
				ot.setCreateTime("");
			}
			if(o.getEntryTime()!=null){
				dt = o.getEntryTime();
				ot.setEntryTime(sdf.format(dt));
			}else{
				ot.setEntryTime("");
			}
			ot.setStatus(o.getStatus().toString());
			listOrdersDTO.add(ot);
		}
		return listOrdersDTO;
	}

	@Override
	public int confirmOrders(OrdersDTO ordersDTO) {
		String orderAmount = ordersDetailMapper.selectSumByOrderId(ordersDTO.getId());
		Orders ordersDO = new Orders();
		ordersDO.setId(ordersDTO.getId());
		ordersDO.setStatus(1);
		BigDecimal bd=new BigDecimal(orderAmount);
		ordersDO.setOrderAmount( bd);
		ordersDO.setEntryTime(new Date());
		return ordersMapper.updateByPrimaryKeySelective(ordersDO);
	}

	@Override
	public int invalidOrders(OrdersDTO ordersDTO) {
		//入库
		int i=0;
		int orderID =ordersDTO.getId();
		List<OrdersDetail> listOrdersDetail=ordersDetailMapper.selectByOrderID(orderID);
		for(OrdersDetail od:listOrdersDetail){
			Goods goods = new Goods();
			goods.setId(od.getGoodsId());
			goods.setGoodsStock(od.getNumber());
			i = goodsMapper.updateAdStockById(goods);
		}
		if(i>0){
			Orders ordersDO = new Orders();
			ordersDO.setId(ordersDTO.getId());
			ordersDO.setStatus(2);
			ordersDO.setEntryTime(new Date());
			i = ordersMapper.updateByPrimaryKeySelective(ordersDO);
		}
		
		return i;
	}
	
	
}
